{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MhoQ0WE77laV"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "_ckMIh7O7s6D"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jYysdyb-CaWM"
      },
      "source": [
        "# tf.distribute.Strategy with Training Loops"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S5Uhzt6vVIB2"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/r1/tutorials/distribute/training_loops.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/r1/tutorials/distribute/training_loops.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S5Uhzt6vVIB2"
      },
      "source": [
        "> Note: This is an archived TF1 notebook. These are configured\n",
        "to run in TF2's \n",
        "[compatbility mode](https://www.tensorflow.org/guide/migrate)\n",
        "but will run in TF1 as well. To use TF1 in Colab, use the\n",
        "[%tensorflow_version 1.x](https://colab.research.google.com/notebooks/tensorflow_version.ipynb)\n",
        "magic."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FbVhjPpzn6BM"
      },
      "source": [
        "This tutorial demonstrates how to use [`tf.distribute.Strategy`](https://www.tensorflow.org/r1/guide/distribute_strategy) with custom training loops. We will train a simple CNN model on the fashion MNIST dataset. The fashion MNIST dataset contains 60000 train images of size 28 x 28 and 10000 test images of size 28 x 28.\n",
        "\n",
        "We are using custom training loops to train our model because they give us flexibility and a greater control on training. Moreover, it is easier to debug the model and the training loop."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dzLKpmZICaWN"
      },
      "outputs": [],
      "source": [
        "# Import TensorFlow\n",
        "import tensorflow.compat.v1 as tf\n",
        "\n",
        "\n",
        "# Helper libraries\n",
        "import numpy as np\n",
        "import os\n",
        "\n",
        "print(tf.__version__)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MM6W__qraV55"
      },
      "source": [
        "## Download the fashion mnist dataset"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7MqDQO0KCaWS"
      },
      "outputs": [],
      "source": [
        "fashion_mnist = tf.keras.datasets.fashion_mnist\n",
        "\n",
        "(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\n",
        "\n",
        "# Adding a dimension to the array -> new shape == (28, 28, 1)\n",
        "# We are doing this because the first layer in our model is a convolutional\n",
        "# layer and it requires a 4D input (batch_size, height, width, channels).\n",
        "# batch_size dimension will be added later on.\n",
        "train_images = train_images[..., None]\n",
        "test_images = test_images[..., None]\n",
        "\n",
        "# Getting the images in [0, 1] range.\n",
        "train_images = train_images / np.float32(255)\n",
        "test_images = test_images / np.float32(255)\n",
        "\n",
        "train_labels = train_labels.astype('int64')\n",
        "test_labels = test_labels.astype('int64')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4AXoHhrsbdF3"
      },
      "source": [
        "## Create a strategy to distribute the variables and the graph"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5mVuLZhbem8d"
      },
      "source": [
        "How does `tf.distribute.MirroredStrategy` strategy work?\n",
        "\n",
        "*   All the variables and the model graph is replicated on the replicas.\n",
        "*   Input is evenly distributed across the replicas.\n",
        "*   Each replica calculates the loss and gradients for the input it received.\n",
        "*   The gradients are synced across all the replicas by summing them.\n",
        "*   After the sync, the same update is made to the copies of the variables on each replica.\n",
        "\n",
        "Note: You can put all the code below inside a single scope. We are dividing it into several code cells for illustration purposes.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "F2VeZUWUj5S4"
      },
      "outputs": [],
      "source": [
        "# If the list of devices is not specified in the\n",
        "# `tf.distribute.MirroredStrategy` constructor, it will be auto-detected.\n",
        "strategy = tf.distribute.MirroredStrategy()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZngeM_2o0_JO"
      },
      "outputs": [],
      "source": [
        "print ('Number of devices: {}'.format(strategy.num_replicas_in_sync))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "k53F5I_IiGyI"
      },
      "source": [
        "## Setup input pipeline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0Qb6nDgxiN_n"
      },
      "source": [
        "When training a model with multiple GPUs, you can use the extra computing power effectively by increasing the batch size. In general, use the largest batch size that fits the GPU memory, and tune the learning rate accordingly."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jwJtsCQhHK-E"
      },
      "outputs": [],
      "source": [
        "BUFFER_SIZE = len(train_images)\n",
        "\n",
        "BATCH_SIZE_PER_REPLICA = 64\n",
        "BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync\n",
        "\n",
        "EPOCHS = 10"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "J7fj3GskHC8g"
      },
      "source": [
        "`tf.distribute.Strategy.experimental_distribute_dataset` evenly distributes the dataset across all the replicas."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WYrMNNDhAvVl"
      },
      "outputs": [],
      "source": [
        "train_dataset = tf.data.Dataset.from_tensor_slices(\n",
        "(train_images, train_labels)).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)\n",
        "train_ds = strategy.experimental_distribute_dataset(train_dataset)\n",
        "\n",
        "test_dataset = tf.data.Dataset.from_tensor_slices(\n",
        "    (test_images, test_labels)).batch(BATCH_SIZE)\n",
        "test_ds = strategy.experimental_distribute_dataset(test_dataset)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bAXAo_wWbWSb"
      },
      "source": [
        "## Model Creation\n",
        "\n",
        "Create a model using `tf.keras.Sequential`. You can also use the Model Subclassing API to do this."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9ODch-OFCaW4"
      },
      "outputs": [],
      "source": [
        "with strategy.scope():\n",
        "  model = tf.keras.Sequential([\n",
        "      tf.keras.layers.Conv2D(32, 3, activation='relu',\n",
        "                             input_shape=(28, 28, 1)),\n",
        "      tf.keras.layers.MaxPooling2D(),\n",
        "      tf.keras.layers.Conv2D(64, 3, activation='relu'),\n",
        "      tf.keras.layers.MaxPooling2D(),\n",
        "      tf.keras.layers.Flatten(),\n",
        "      tf.keras.layers.Dense(64, activation='relu'),\n",
        "      tf.keras.layers.Dense(10, activation='softmax')\n",
        "    ])\n",
        "  optimizer = tf.train.GradientDescentOptimizer(0.001)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e-wlFFZbP33n"
      },
      "source": [
        "## Define the loss function\n",
        "\n",
        "Normally, on a single machine with 1 GPU/CPU, loss is divided by the number of examples in the batch of input.\n",
        "\n",
        "*So, how should the loss be calculated when using a `tf.distribute.Strategy`?*\n",
        "\n",
        "* For an example, let's say you have 4 GPU's and a batch size of 64. One batch of input is distributed\n",
        "across the replicas (4 GPUs), each replica getting an input of size 16.\n",
        "\n",
        "* The model on each replica does a forward pass with its respective input and calculates the loss. Now, instead of dividing the loss by the number of examples in its respective input (BATCH_SIZE_PER_REPLICA = 16), the loss should be divided by the GLOBAL_BATCH_SIZE (64).\n",
        "\n",
        "*Why do this?*\n",
        "\n",
        "* This needs to be done because after the gradients are calculated on each replica, they are synced across the replicas by **summing** them.\n",
        "\n",
        "*How to do this in TensorFlow?*\n",
        "* If you're writing a custom training loop, as in this tutorial, you should sum the per example losses and divide the sum by the GLOBAL_BATCH_SIZE: \n",
        "`scale_loss = tf.reduce_sum(loss) * (1. / GLOBAL_BATCH_SIZE)` or you can use `tf.nn.compute_average_loss` which takes the per example loss,\n",
        "optional sample weights, and GLOBAL_BATCH_SIZE as arguments and returns the scaled loss.\n",
        "\n",
        "* If you are using regularization losses in your model then you need to scale\n",
        "the loss value by number of replicas. You can do this by using the `tf.nn.scale_regularization_loss` function.\n",
        "\n",
        "* Using `tf.reduce_mean` is not recommended. Doing so divides the loss by actual per replica batch size which may vary step to step.\n",
        "\n",
        "* This reduction and scaling is done automatically in keras `model.compile` and `model.fit`\n",
        "\n",
        "* If using `tf.keras.losses` classes, the loss reduction needs to be explicitly specified to be one of `NONE` or `SUM`. `AUTO` and `SUM_OVER_BATCH_SIZE`  are disallowed when used with `tf.distribute.Strategy`. `AUTO` is disallowed because the user should explicitly think about what reduction they want to make sure it is correct in the distributed case. `SUM_OVER_BATCH_SIZE` is disallowed because currently it would only divide by per replica batch size, and leave the dividing by number of replicas to the user, which might be easy to miss. So instead we ask the user do the reduction themselves explicitly."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iuKuNXPORfqJ"
      },
      "source": [
        "## Training loop"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "47BLVkRkVQDO"
      },
      "outputs": [],
      "source": [
        "with strategy.scope():\n",
        "  def train_step(dist_inputs):\n",
        "    def step_fn(inputs):\n",
        "      images, labels = inputs\n",
        "      logits = model(images)\n",
        "      cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n",
        "          logits=logits, labels=labels)\n",
        "      loss = tf.nn.compute_average_loss(cross_entropy, global_batch_size=BATCH_SIZE)\n",
        "      train_op = optimizer.minimize(loss)\n",
        "      with tf.control_dependencies([train_op]):\n",
        "        return tf.identity(loss)\n",
        "\n",
        "    per_replica_losses = strategy.run(\n",
        "        step_fn, args=(dist_inputs,))\n",
        "    mean_loss = strategy.reduce(\n",
        "        tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)\n",
        "    return mean_loss"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7x7s5iYAYSGD"
      },
      "outputs": [],
      "source": [
        "with strategy.scope():\n",
        "  train_iterator = train_ds.make_initializable_iterator()\n",
        "  iterator_init = train_iterator.initializer\n",
        "  var_init = tf.global_variables_initializer()\n",
        "  loss = train_step(next(train_iterator))\n",
        "  with tf.Session() as sess:\n",
        "    sess.run([var_init])\n",
        "    for epoch in range(EPOCHS):\n",
        "        sess.run([iterator_init])\n",
        "        for step in range(10000):\n",
        "          if step % 1000 == 0:\n",
        "            print('Epoch {} Step {} Loss {:.4f}'.format(epoch+1,\n",
        "                                                        step,\n",
        "                                                        sess.run(loss)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6hEJNsokjOKs"
      },
      "source": [
        "## Next Steps\n",
        "\n",
        "Try out the new `tf.distribute.Strategy` API on your models."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "training_loops.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
